<?php

namespace common\extended\system;

class Util
{
    /**
     * 正则方法 获取字符串的长度
     * @param string $string  字符串（ 中文、字母、字母混合都可以 ）
     * @return int
     */
    public static function utf8_strlen($string)
    {
        preg_match_all("/./us", $string, $match);
        return count($match[0]);
    }

    /**
     * 截取中文字符长度
     * @param string $string 截取的字符串
     * @param int $length 保留的长度
     * @param string $etc 省略字符
     * @return string 截取后得字符串
     */
    public static function truncate_utf8_string($string, $length, $etc = '...')
    {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
        {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
            {
                if ($length < 1.0)
                {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            }
            else
            {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen)
        {
            $result .= $etc;
        }
        return $result;
    }

    /**
     * 字符串加密
     */
    public static function strEncryption($str, $jamStr = '')
    {
        if ($str==""){
            return false;
        }
        if (empty($jamStr))
        {
            $jamStr = 'fobcart';
        }
        return md5(md5($str) . $jamStr);
    }

    /**
     * 返回单个错误信息
     * @param array $error rules方法验证没有通过的错误信息数组
     * @return string
     */
    public static function handelErrors($error){
        if ($error && is_array($error)) {
            foreach ($error as $err) {
                return $err[0];
            }
        }
        return '';
    }
    /**
     * 检查手机号格式
     * @date: 2016-2-25 
     * @author: futao
     */
    public static function checkMobile($mobile)
    {
    	if (!preg_match("/^1\d{10}$/", $mobile)) {
    		return false;
    	}
    	return true;
    }
    /**
     * 根据时间获取一周的时间段
     * @date: 2016-2-25 
     * @author: futao
     */
    public static function getWeek($week)
    {
    	$timeStamp = strtotime($week);
    	$startDate = date("Y-m-d",mktime(0, 0 , 0,date("m",$timeStamp),date("d",$timeStamp)-date("w",$timeStamp)+1,date("Y",$timeStamp)));
    	$endDate = date("Y-m-d",mktime(23,59,59,date("m",$timeStamp),date("d",$timeStamp)-date("w",$timeStamp)+7,date("Y",$timeStamp)));
    	return $startDate."至".$endDate;
    }
    /**
     * 获取一年的时间段
     * @date: 2016-3-17 
     * @author: futao
     */
    public static function getYear()
    {
    	$theYear = date('Y');
    	return $theYear.'-1-1 00:00:00 至 '.$theYear.'-12-31 23:59:59';
    }
    /**
     * 获取一天的时间段
     * @date: 2016-3-15 
     * @author: futao
     */

    public static function getDay()
    {
    	$todayDate = date('Y-m-d');
    	return $todayDate.' 00:00:00 至 '.$todayDate.' 23:59:59';
    }

    /**
     * 根据时间获取一月的时间段
     * @date: 2016-2-25 
     * @author: futao
     */
	public static function getMonth($month)
	{
		$timeStamp = strtotime($month);
		$startDate = date("Y-m-d",mktime(0, 0 , 0,date("m",$timeStamp),1,date("Y",$timeStamp)));
		$endDate = date("Y-m-d",mktime(23,59,59,date("m",$timeStamp),date("t",$timeStamp),date("Y",$timeStamp)));
		return $startDate."至".$endDate;
	}
	/**
	 * 获取标识号
	 * @date: 2016年2月29日 
	 * @author: chenxiaolin
	 */
	public static function getSerialNumber($uid){
	    $date = date('YmdHis');
	    return $uid.$date;
	}

    /**
     * 计算两个日期之间的相差天数
     * @param string $date1 日期1
     * @param string $date2 日期2
     * @return float
     */
    public static function differDate($date1, $date2)
    {
        $Date_List_a1 = explode("-", $date1);
        $Date_List_a2 = explode("-", $date2);
        $d1 = mktime(0, 0, 0, $Date_List_a1[1], $Date_List_a1[2], $Date_List_a1[0]);
        $d2 = mktime(0, 0, 0, $Date_List_a2[1], $Date_List_a2[2], $Date_List_a2[0]);
        return round(($d1-$d2)/3600/24);
    }
    
    /**
     * 导出Excel:输出到浏览器
     * @date: 2016年2月27日
     * @author: chenxiaolin
     */
    public static function browser_export($type,$filename){
        if($type=="Excel5"){
            header('Content-Type: application/vnd.ms-excel');//告诉浏览器将要输出excel03文件
        }else{
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器数据excel07文件
        }
        header('Content-Disposition: attachment;filename="'.$filename.'"');//告诉浏览器将输出文件的名称
        header('Cache-Control: max-age=0');//禁止缓存
    }
    
    /**
     * post请求
     * @date: 2016年3月21日 
     * @author: chenxiaolin
     */
    public static function httpPost($url, $params) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        if(is_array($params)) {
            $postBody = http_build_query($params);
        } else if($params) {
            $postBody = strval($params);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
        $headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        if(curl_errno($ch)) {
            throw new \Exception(curl_error($ch), 0);
        } else {
            $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if($statusCode !== 200) {
                throw new \Exception($response, $statusCode);
            }
        }
        curl_close($ch);
        return $response;
    }
}
